package com.kpx.app.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.kpx.app.R;
import com.kpx.app.adapter.PayAdapter;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.LoginUser;
import com.kpx.app.bean.OrderBean;
import com.kpx.app.bean.PayInfoBean;
import com.kpx.app.bean.PayResult;
import com.kpx.app.bean.PointPayInfo;
import com.kpx.app.bean.Wallet;
import com.kpx.app.configs.Constants;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.thirdparty.alipay.AlipayPay;
import com.kpx.app.thirdparty.wechat.WechatPay;
import com.kpx.app.thirdparty.wechat.utils.WechatConstants;
import com.kpx.app.thirdparty.wechat.utils.WechatParam;
import com.kpx.app.utils.MD5Util;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.UIUtils;
import com.kpx.app.utils.UserInfoUtils;
import com.kpx.app.utils.uiutils.IntentUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.TitleView;
import com.kpx.app.wigdet.DialogWithdrawInputPwd;
import com.kpx.app.wigdet.SlipButton;
import com.kpx.app.wxapi.WXPayEntryActivity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by congdy on 17/3/19.
 * 支付列表
 */

public class ActivityPayList extends ActivityBase {
    @BindView(R.id.titleview)
    TitleView titleview;
    @BindView(R.id.txt_pay_type)
    TextView txtPayType;
    @BindView(R.id.txt_pay_price)
    TextView txtPayPrice;
    @BindView(R.id.listview_pay)
    ListView listviewPay;
    @BindView(R.id.btn_suborder)
    Button btnSuborder;
    @BindView(R.id.txt_point_go)
    TextView txtPointGo;
    @BindView(R.id.sw_point)
    SlipButton swPoint;
    @BindView(R.id.ll_show_point1)
    LinearLayout llShowPoint1;
    @BindView(R.id.txt_point_min)
    TextView txtPointMin;
    @BindView(R.id.txt_rel_pay)
    TextView txtRelPay;
    @BindView(R.id.txt_wallet_price)
    TextView txt_wallet_price;
    @BindView(R.id.ll_show_point2)
    LinearLayout llShowPoint2;
    private OrderBean b;
    private List<PayInfoBean> plist = new ArrayList<>();
    private PayAdapter adapter;
    public static PayInfoBean selectPay;
    private int mixPay = 0;
    public static double relprice;
    private PointPayInfo payInfo;
    DecimalFormat df = new DecimalFormat("###0.00");


    @Override
    public void initview(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_pay_list);
        ButterKnife.bind(this);
        relprice = 0;
        UIUtils.setNormalTitle(titleview, "支付");
        adapter = new PayAdapter(this, plist, R.layout.item_pay_list);
        listviewPay.setAdapter(adapter);
        swPoint.SetOnChangedListener(new SlipButton.OnChangedListener() {
            @Override
            public void OnChanged(View v, boolean isChecked) {
                mixPay = isChecked ? 1 : 0;
                llShowPoint2.setVisibility(isChecked ? View.VISIBLE : View.GONE);
                relprice = isChecked ? b.getPaymentPrice() - payInfo.getDeductionPrice() : b.getPaymentPrice();
                txtRelPay.setText("¥" + df.format(relprice));
            }
        });
        txt_wallet_price.setText(df.format(UserInfoUtils.getCachedLoginUser().getWALLET().getCashAmount())+"");
    }

    @Override
    public void initData() {
        b = (OrderBean) getIntent().getExtras().getSerializable(Constants.KEY_ORDER_BEAN);
        if (b != null) {
            WechatConstants.ORDER_ID = b.getDmId();
            txtPayPrice.setText("¥" + df.format(b.getDeposit()));
            relprice = b.getDeposit();
            UserInfoUtils.getMyWallet(this, new UserInfoUtils.OnGetMyWalletBackListener() {
                @Override
                public void back(Wallet aBeans) {
                    if (aBeans != null) {
                        LoginUser loginUser = UserInfoUtils.getCachedLoginUser();
                        loginUser.setWALLET(aBeans);
                        UserInfoUtils.saveLoginUser(loginUser);
                        adapter.notifyDataSetChanged();
                    }
                    getPayList();
                }
            });
        }
    }

    /**
     * 获取支付信息
     */
    private void getPayInfo() {
        showLoadingDialog();
        MyHashMap map = new MyHashMap();
        map.put("orderId", b.getDmId() + "");
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    payInfo = (PointPayInfo) result.getData();
                    if (payInfo != null) {
                        txtPointGo.setText(payInfo.getShowText());
                        txtPointMin.setText("¥-" + df.format(payInfo.getDeductionPrice()));
                        relprice = b.getPaymentPrice();
                        adapter.notifyDataSetChanged();
                        txtRelPay.setText("¥" + relprice);
                        if (payInfo.getDeductionPrice() == 0) {
                            swPoint.setEnabled(false);
//                            llShowPoint1.setVisibility(View.VISIBLE);
                        } else {
//                            llShowPoint1.setVisibility(View.GONE);
                        }
                    }
                } else {
                    ToastUtil.getInstance().showToast(ActivityPayList.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityPayList.this, error);
            }

        }, PointPayInfo.class, HttpDataRequest.TYPE_OBJECT).POST(HttpDataReqUrl.URL_POST_GET_PAY_INFO, true, map);
    }

    /**
     * 获取支付列表
     */
    private void getPayList() {
        showLoadingDialog();
        MyHashMap map = new MyHashMap();
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                getPayInfo();
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    ArrayList<PayInfoBean> list = (ArrayList<PayInfoBean>) result.getData();
                    if (list != null) {
                        plist.addAll(list);
                        if (plist.size() > 0) {
                            for (int i = 0; i < plist.size(); i++) {
                                if (plist.get(i).getPayCode() != 10) {
                                    selectPay = plist.get(i);
                                    plist.get(i).setIschecked(true);
                                    break;
                                }
                            }
                        }
                        adapter.setData(plist);
                    }
                } else {
                    ToastUtil.getInstance().showToast(ActivityPayList.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                getPayInfo();
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityPayList.this, error);
            }

        }, PayInfoBean.class, HttpDataRequest.TYPE_LIST).POST(HttpDataReqUrl.URL_POST_POST_PAY_LIST, true, map);
    }

    @Override
    public void onReceiver(Context context, Intent intent) {

    }

    @OnClick(R.id.btn_suborder)
    public void onClick() {
        if (plist.size() == 0) {
            return;
        }
        if (selectPay == null) {
            return;
        }

//        if (selectPay.getPayCode() == 1) {
//            ToastUtil.getInstance().showToast(this, "暂未开放");
//            return;
//        }

        showLoadingDialog();
        MyHashMap map = new MyHashMap();
        map.put("payType", selectPay.getPayCode() + "");
        map.put("orderId", b.getDmId() + "");
        map.put("mixPay", mixPay + "");
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    if (UserInfoUtils.getCachedLoginUser().getWALLET().getCashAmount() >= relprice) {
                        toOrderList();
                        ToastUtil.getInstance().showToast(ActivityPayList.this, "支付成功");
                        return;
                    }
                    if (selectPay.getPayCode() == 3) {
                        WechatParam p = (WechatParam) result.getData();
                        if (p != null) {
                            wechatPay(p);
                        }
                    } else {
                        aliPay(JSON.toJSONString(result.getData()));
                    }
                } else {
                    ToastUtil.getInstance().showToast(ActivityPayList.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityPayList.this, error);
            }

        }, selectPay.getPayCode() == 3 ? WechatParam.class : null, selectPay.getPayCode() == 3 ? HttpDataRequest.TYPE_OBJECT : null).POST(HttpDataReqUrl.URL_POST_POST_PAY_PARAMS, true, map);

    }

    /**
     * pwd(钱包密码),orderId(订单),paymentMethod(支付类型，由支付列表来)
     */
    private void toWalletPay() {
        final DialogWithdrawInputPwd pwdd = new DialogWithdrawInputPwd(this);
        pwdd.setAmount(relprice + "");
        pwdd.setOnInputListener(new DialogWithdrawInputPwd.OnInputListener() {
            @Override
            public void inputDone(String pwd) {
                pwdd.dismiss();
                showLoadingDialog();
                MyHashMap map = new MyHashMap();//pwd(钱包密码),orderId(订单),paymentMethod(支付类型，由支付列表来)
                map.put("pwd", MD5Util.encrypt(pwd));
                map.put("orderId", b.getDmId() + "");
                map.put("paymentMethod", selectPay.getPayCode() + "");
                new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
                    @Override
                    public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                        dissmissLoadingDialog();
                        if (result.getCode() == 0) {
                            toOrderList();
                            ToastUtil.getInstance().showToast(ActivityPayList.this, "支付成功");
                        } else {
                            ToastUtil.getInstance().showToast(ActivityPayList.this, result.getMsg());
                        }
                    }

                    @Override
                    public void onRequestError(String url, int statusCode, String error) {
                        dissmissLoadingDialog();
                        ToastUtil.getInstance().showToast(ActivityPayList.this, error);
                    }

                }, null, null).POST(HttpDataReqUrl.URL_POST_POST_PAY_WALLET, true, map);
            }
        });
        pwdd.show();

    }

    private void aliPay(String param) {
        AlipayPay.pay(this, param.replace("\"",""), mHandler);
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            @SuppressWarnings("unchecked")
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            /**
             * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
             * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
             * docType=1) 建议商户依赖异步通知
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息

            String resultStatus = payResult.getResultStatus();
            // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
            if (TextUtils.equals(resultStatus, "9000")) {
                Toast.makeText(ActivityPayList.this, "支付成功", Toast.LENGTH_SHORT).show();
                toOrderList();
            } else {
                // 判断resultStatus 为非"9000"则代表可能支付失败
                // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                if (TextUtils.equals(resultStatus, "8000")) {
                    Toast.makeText(ActivityPayList.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                } else {
                    // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                    Toast.makeText(ActivityPayList.this, "支付失败", Toast.LENGTH_SHORT).show();

                }
            }
        }
    };

    /**
     * 调用微信SDK支付
     *
     * @param wechatParam
     */
    private void wechatPay(WechatParam wechatParam) {
        if (null == wechatParam
                || TextUtils.isEmpty(wechatParam.getAppId())
                || TextUtils.isEmpty(wechatParam.getPartnerId())
                || TextUtils.isEmpty(wechatParam.getPrepayId())
                || TextUtils.isEmpty(wechatParam.getPackageValue())
                || TextUtils.isEmpty(wechatParam.getNonceStr())
                || TextUtils.isEmpty(wechatParam.getTimeStamp())
                || TextUtils.isEmpty(wechatParam.getSign())) {
            ToastUtil.getInstance().showToast(this, R.string.pay_param_incomplete);
            return;
        }
        WechatConstants.ORDER_ID = b.getDmId();
        showLoadingDialog("支付中...");
        WechatPay wechatPay = new WechatPay(this, wechatParam);
        wechatPay.pay();
        dissmissLoadingDialog();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /**
     * 跳转到订单结果页
     */
    private void toOrderList() {
        closeAllOpenedActivityNoMain();
        IntentUtil.gotoActivityAndFinish(ActivityPayList.this, ActivityPayResult.class);
    }
}
